package za.org.jcicada.comms.impl.inprocess;

import java.io.IOException;
import java.net.URI;

import za.org.jcicada.comms.IConnection;
import za.org.jcicada.comms.IConnector;
import za.org.jcicada.comms.impl.ConnectorFactory;

/**
 * In process connector requires a handle to an acceptor. It can then connect
 * directly to the acceptor when it creates the client connection.
 */
public class InProcessConnector implements IConnector {
	
    private InProcessAcceptor acceptor;
    
    /**
     * Construct connector with handle to acceptor
     * @param acceptor
     */
    public InProcessConnector(InProcessAcceptor acceptor) {
        if (acceptor == null) {
            throw new IllegalArgumentException("Acceptor can't be null");
        }
        this.acceptor = acceptor;
    }
    
    /**
     * Construct connector using location URI. Tries to retrieve the acceptor
     * from the connectorFactory
     * 
     * @param locationURI 
     */
    public InProcessConnector(URI locationURI) {
        acceptor = ConnectorFactory.getInProcessAcceptor(locationURI);
        if (acceptor == null) {
            throw new IllegalStateException("Can't locate acceptor for " + locationURI.toString());
        }
    }

    @Override
    public IConnection connect() throws IOException {
        InProcessConnection connection = new InProcessConnection();
        acceptor.connect(connection);
        return connection;
    }
    
}
